Chart for WPF and Silverlight > Chart Features > Markers and Labels > Adding Markers in Code |
The topics above all describe how to add a marker using XAML markup. You might have a project that requires you to add a marker in code.
First, you need to create a new ChartPanel:
C# |
Copy Code
|
---|---|
var pnl = new ChartPanel(); |
Once you've added a new ChartPanel, you'll add a new ChartPanelObject and set the alignment:
C# |
Copy Code
|
---|---|
var obj = new ChartPanelObject() { HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Bottom }; |
Next, you'll add a border element:
C# |
Copy Code
|
---|---|
var bdr = new Border() { Background = new SolidColorBrush(Colors.Green) { Opacity = 0.4 }, BorderBrush = new SolidColorBrush(Colors.Green), BorderThickness = new Thickness(1, 1, 3, 3), CornerRadius = new CornerRadius(6, 6, 0, 6), Padding = new Thickness(3) }; |
Add a StackPanel element that contains two TextBlock controls. Note that the binding source is your ChartPanelObject:
C# |
Copy Code
|
---|---|
var sp = new StackPanel(); var tb1 = new TextBlock(); var bind1 = new Binding(); bind1.Source = obj; bind1.StringFormat = "x={0:#.##}"; bind1.Path = new PropertyPath("DataPoint.X"); tb1.SetBinding(TextBlock.TextProperty, bind1); var tb2 = new TextBlock(); var bind2 = new Binding(); bind2.Source = obj; bind2.StringFormat = "y={0:#.##}"; bind2.Path = new PropertyPath("DataPoint.Y"); tb2.SetBinding(TextBlock.TextProperty, bind2); sp.Children.Add(tb1); sp.Children.Add(tb2); bdr.Child = sp; |
Set the ChartPanelObject's Content, DataPoint, and Action properties, and then add the ChartPanelObject to the ChartPanel. The last line of code adds the collection of layers to your chart control.
C# |
Copy Code
|
---|---|
obj.Content = bdr;
obj.DataPoint = new Point();
obj.Action = ChartPanelAction.MouseMove;
pnl.Children.Add(obj);
chart.View.Layers.Add(pnl);
|
The last line of code you need sets the Attach property:
C# |
Copy Code
|
---|---|
obj.Attach = ChartPanelAttach.MouseMove; }; } } |
With the code in this topic, you've created a chart marker that will follow your mouse.